#include "addroutedialog.h"
#include "ui_addroutedialog.h"

AddRouteDialog::AddRouteDialog(const QList <Point> &aPointList, QWidget *parent) :
    QDialog(parent), ui(new Ui::AddRouteDialog), formPointList(aPointList)
{
    unsigned long N = formPointList.size();
    ui->setupUi(this);
    for(unsigned long i = 0; i < N; ++i)
    {
        QListWidgetItem *item = new QListWidgetItem(formPointList[i].GetName(), ui->allPointListWidget);
        item->setData(Qt::UserRole, static_cast<int>(i));
        item->setText(formPointList[i].GetName());
    }
    ui->allPointListWidget->sortItems();
    setFixedSize(size());
}

AddRouteDialog::~AddRouteDialog()
{
    if(ui)  delete ui;
    formPointList.clear();
}

bool AddRouteDialog::Result(Route *aRoute, bool &aSetCurrent) const
{
    if(aRoute)
    {
        aRoute->ClearRoute();
        // установка полученных значений
        aRoute->SetName(ui->routeNameLineEdit->text());
        unsigned long N = ui->routePointListWidget->count();
        for(unsigned long i = 0; i < N; ++i)
        {
            unsigned long tmpID = formPointList[ui->routePointListWidget->item(i)->data(Qt::UserRole).toInt()].GetID();
            aRoute->AddPoint(tmpID);
        }
        N = ui->fileListWidget->count();
        for(unsigned long i = 0; i < N; ++i)
            aRoute->AddFile(ui->fileListWidget->item(i)->data(Qt::UserRole).toString());
        aSetCurrent = ui->setCurrentCheckBox->isChecked();
        return true;
    }
    else
        return false;
}

void AddRouteDialog::on_linkfileButton_clicked()
{
    // получение имени файла
    QString fileName = QFileDialog::getOpenFileName(this, tr("Привязать файл"), "", tr("Все файлы (*.*)"));
    if(fileName.compare(""))
    {
        // проверка повторного включения имени файла
        unsigned long N = ui->fileListWidget->count();
        for(unsigned long i = 0; i < N; ++i)
            if(!fileName.compare(ui->fileListWidget->item(i)->data(Qt::UserRole).toString()))
                return;
        // добавление имени файла
        QListWidgetItem *item = new QListWidgetItem(fileName, ui->fileListWidget);
        item->setData(Qt::UserRole, fileName);
        item->setWhatsThis("FILE");
    }
    ui->deleteFileButton->setEnabled(ui->fileListWidget->count() > 0);
}

void AddRouteDialog::on_deleteFileButton_clicked()
{
    QListWidgetItem *item = ui->fileListWidget->currentItem();
    if(item)    delete item;
    ui->deleteFileButton->setEnabled(ui->fileListWidget->count() > 0);
}

void AddRouteDialog::on_addPointButton_clicked()
{
    if(ui->allPointListWidget->count() && ui->allPointListWidget->currentItem())
    {
        QListWidgetItem *item = new QListWidgetItem(*(ui->allPointListWidget->currentItem()));
        ui->routePointListWidget->addItem(item);
        item = ui->allPointListWidget->currentItem();
        delete item;
        ui->allPointListWidget->sortItems();
        ui->saveButton->setEnabled(IsEnabledToSave());
    }
}

void AddRouteDialog::on_removePointButton_clicked()
{
    if(ui->routePointListWidget->count() && ui->routePointListWidget->currentItem())
    {
        QListWidgetItem *item = new QListWidgetItem(*(ui->routePointListWidget->currentItem()));
        ui->allPointListWidget->addItem(item);
        item = ui->routePointListWidget->currentItem();
        delete item;
        ui->allPointListWidget->sortItems();
        ui->saveButton->setEnabled(IsEnabledToSave());
    }
}

void AddRouteDialog::on_upPointButton_clicked()
{
    int number = ui->routePointListWidget->currentRow();
    if(number > 0)
    {
        QListWidgetItem *item = ui->routePointListWidget->takeItem(number);
        ui->routePointListWidget->insertItem(--number, item);
        ui->routePointListWidget->setCurrentItem(item);
    }
}

void AddRouteDialog::on_downPointButton_clicked()
{
    int number = ui->routePointListWidget->currentRow();
    if(number < ui->routePointListWidget->count())
    {
        QListWidgetItem *item = ui->routePointListWidget->takeItem(number);
        ui->routePointListWidget->insertItem(++number, item);
        ui->routePointListWidget->setCurrentItem(item);
    }
}

void AddRouteDialog::on_routeNameLineEdit_textChanged(const QString& /*arg1*/)
{
    ui->saveButton->setEnabled(IsEnabledToSave());
}

void AddRouteDialog::on_pointFindLineEdit_returnPressed()
{
    if(!ui->pointFindLineEdit->text().isEmpty())
    {
        unsigned long findStartNumber = ui->allPointListWidget->currentRow(), N = ui->allPointListWidget->count();
        for(unsigned long i = ++findStartNumber; i < N; ++i)
        {
            QString tmpString = ui->allPointListWidget->item(i)->text();
            tmpString.resize(ui->pointFindLineEdit->text().size());
            if(!tmpString.compare(ui->pointFindLineEdit->text()))
            {
                ui->allPointListWidget->setCurrentRow(i);
                return;
            }
        }
        for(unsigned long i = 0; i < findStartNumber; ++i)
        {
            QString tmpString = ui->allPointListWidget->item(i)->text();
            tmpString.resize(ui->pointFindLineEdit->text().size());
            if(!tmpString.compare(ui->pointFindLineEdit->text()))
            {
                ui->allPointListWidget->setCurrentRow(i);
                return;
            }
        }
    }
}

bool AddRouteDialog::IsEnabledToSave(void) const
{
    return  (!ui->routeNameLineEdit->text().isEmpty() && (ui->routePointListWidget->count() > 1));
}

void AddRouteDialog::on_fileListWidget_doubleClicked(const QModelIndex& /*index*/)
{
    QListWidgetItem *item = ui->fileListWidget->currentItem();
    if(item && (item->whatsThis() == "FILE"))
    {
        QString file_name = item->data(Qt::UserRole).toString();
        file_name = QDir::cleanPath(file_name);
        if(!QFile::exists(file_name))
        {
            QMessageBox::warning(QApplication::activeWindow(), QApplication::applicationName(),
            "Невозможно открыть файл `" + file_name + "`. Файл не существует!");
            return;
        }
        if(!QDesktopServices::openUrl(QUrl(QUrl::fromLocalFile(file_name))))
        {
            QMessageBox::information(QApplication::activeWindow(), QApplication::applicationName(),
            "Невозможно открыть файл `" + file_name + "`. Не найдена программа для его открытия!");
            return;
        }
    }
}

void AddRouteDialog::on_allPointListWidget_currentRowChanged(int currentRow)
{
    ui->addPointButton->setEnabled(currentRow != -1);
    ui->removePointButton->setEnabled(currentRow != -1);
}

void AddRouteDialog::on_routePointListWidget_currentRowChanged(int currentRow)
{
    ui->downPointButton->setEnabled(currentRow != -1);
    ui->upPointButton->setEnabled(currentRow != -1);
}
